package com.woniu.adopt_web.controller;

import com.github.pagehelper.PageInfo;
import com.woniu.adopt_web.entity.Comment;
import com.woniu.adopt_web.entity.Pet;
import com.woniu.adopt_web.service.CommentService;
import com.woniu.adopt_web.vo.CommentVo;
import com.woniu.adopt_web.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @RequestMapping("/list")
    public String list(@RequestParam(value = "now" ,defaultValue = "1")Integer now ,
                       @RequestParam(value = "size" ,defaultValue = "3")Integer size,
                       Model model){
        PageInfo<CommentVo> commentVoPageInfo = commentService.queryAllByPage(now,size);
        model.addAttribute("pageComment",commentVoPageInfo);
        return "comment";
    }

    @RequestMapping("/listPet")
    public String listPet(@RequestParam(value = "now" ,defaultValue = "1")Integer now ,
                          @RequestParam(value = "size" ,defaultValue = "3")Integer size,
                          Model model, HttpSession session){
        PageInfo<Pet> petPageInfo = commentService.queryPetAllByPage(now,size);
        System.out.println(petPageInfo+"     ---------------------");
        model.addAttribute("pagePet",petPageInfo);
        UserVo loginUser = (UserVo) session.getAttribute("loginUser");
        if(loginUser!=null){
            session.setAttribute("User", loginUser);
        }else {
            UserVo userVo = new UserVo();
            userVo.setId(0);
            session.setAttribute("User", userVo);
        }
        return "comment";
    }

    //修改返显
    @RequestMapping("/getCommentByKey")
    @ResponseBody
    public List<CommentVo> getCommentByKey(@RequestParam(value = "id")int id, Model model){
        List<CommentVo> commentVo = commentService.selectCommentByPetKey(id);
        model.addAttribute("pageComment",commentVo);
        return commentVo;
    }

    //修改返显
    @RequestMapping("/save")
    @ResponseBody
    public String save( @RequestParam(value = "pid")int pid, @RequestParam(value = "uid")int uid,@RequestParam(value = "context")String message,Model model){

        if(message == ""){
            return null;
        }else{
            CommentVo commentVo = new CommentVo();
            commentVo.setUserId(uid);
            commentVo.setPetId(pid);
            commentVo.setMessage(message);
            commentVo.setInsertTime(new Date());

            int i = commentService.insertCommentByUIdAndPid(commentVo);
            model.addAttribute("pageComment",commentVo);
            return "ok";
        }

    }
}
